#!/usr/bin/python
# -*- coding: UTF-8 -*-

import db
import config
import os, sys
import json
import subprocess
import time, datetime

isSuspended = False

# 开始执行获取任务，并执行任务
def startRunTask(workRoot):
    # 获取可用的任务
    task = getTask()
    if task:
        try:
            startBuildAndroidOrIOS(workRoot, task)
        except:
            sql = "UPDATE tb_task set status=%d WHERE taskid='%s'" % (3, task["taskid"])
            db.updateRecord(sql)

# 开始服务
def start():
    global isSuspended
    workRoot = config.WORK_ROOT
    if not (workRoot or workRoot == ""):
        print("The config of workRoot is invalid, service aborted.")
        return 

    while (True and (not isSuspended)):
        print("startRunTask")
        startRunTask(workRoot)
        time.sleep(10)

# 停止服务
def stop():
    global isSuspended
    isSuspended = True
    return
    
# 获取可处理的任务
def getTask():
    print("Getting a new task.")
    sql = "SELECT taskid FROM tb_task WHERE status = 1 LIMIT 0, 1"
    result = db.executeSql(sql)
    if (len(result) > 0):
        print("There is one task is running. -- [%s]" % result[0][0])
        return 

    sql = "SELECT taskid, params, type, status, apkurl, iosurl, owner, createtime FROM tb_task WHERE status = 0 limit 0, 1"
    result = db.executeSql(sql)
    if len(result) == 0:
        # 当前没有任务可以处理
        return 
    one = result[0]
    task = {
        "taskid": one[0],
        "params": one[1],
        "type": one[2],
        "status": one[3],
        "apkurl": one[4],
        "iosurl": one[5],
        "owner": one[6],
        "createtime": one[7]
    }
    return task

# 解析参数
def parseParams(params):
    params = json.loads(params)
    strArgs = ""

    allKeys = ["platform", "mode", "gamehallbranch", "lobbybranch", "env", "forceclean", "email", "subhead", "fir_api_token", "pngquant"]
    for key in allKeys:
        val = params[key]
        if key == "platform":
            strArgs = "%s'%s' " % (strArgs, val)
        elif key == "mode":
            strArgs = "%s%s " % (strArgs, val)
        elif key == "gamehallbranch":
            strArgs = "%s%s " % (strArgs, val)
        elif key == "lobbybranch":
            strArgs = "%s%s " % (strArgs, val)
        elif key == "env":
            strArgs = "%s%s " % (strArgs, val)
        elif key == "forceclean":
            strArgs = "%s%s " % (strArgs, "--forceclean")
        elif key == "email":
            if not val or val == "": val = "\"\""
            strArgs = "%s%s %s " % (strArgs, "--email", val)
        elif key == "subhead":
            if not val or val == "": val = "\"\""
            strArgs = "%s%s %s " % (strArgs, "--subhead", val)
        elif key == "fir_api_token":
            if not val or val == "": val = "\"\""
            strArgs = "%s%s %s " % (strArgs, "--firapitoken", val)
        elif key == "pngquant":
            if val == 1:
                strArgs = "%s%s " % (strArgs, "--pngquant")
    return strArgs

# 开始打包，支持Android和IOS
def startBuildAndroidOrIOS(workRoot, task):
    taskid = task["taskid"]
    strArgs = parseParams(task["params"])
    strArgs = "%s%s %s" % (strArgs, "--taskid", taskid)
    print(strArgs)

    sql = "UPDATE tb_task set status=%d WHERE taskid='%s'" % (1, taskid)
    db.updateRecord(sql)

    # os.chdir(workRoot)
    cmd = "cd %s && python autobuild.py %s" % (workRoot, strArgs)
    print(cmd)
    os.system(cmd)

    return strArgs

if __name__ == "__main__":
    start()
